<template>
  <div class="discover-container">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="discover-header">
        <div class="header-content">
          <!-- 左侧返回首页 -->
          <div class="back-home" @click="$router.push('/')">
            <el-icon style="font-size: 24px; margin-top: 5px">
              <ArrowLeft />
            </el-icon>
            <span style="font-size: 24px">回到首页</span>
          </div>
          <!-- 中间搜索框 -->
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索音乐、歌手、专辑"
              class="search-input"
              @keyup.enter="handleEnterSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="danger" class="search-btn" @click="handleSearch">
              搜索
            </el-button>
          </div>

          <!-- 右侧用户信息 -->
          <div class="user-info">
            <div class="login-register" v-if="!ifLogin">
              <span @click="dialogFormVisible = true" style="font-size: 24px">
                登录
              </span>
              <span @click="goToRegister" style="font-size: 24px">注册</span>
            </div>

            <el-dropdown v-else>
              <div class="user-info-content">
                <img
                  src="../images/RecommendList1.png"
                  alt="用户头像"
                  class="user-avatar"
                />
                <span class="user-name">{{ userInfo.userInfoname }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goUserInfo"
                    >个人中心</el-dropdown-item
                  >
                  <el-dropdown-item @click="handleLogout"
                    >退出登录</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <!-- 登录对话框 -->
      <el-dialog v-model="dialogFormVisible" title="登录" width="500">
        <el-form :model="form">
          <el-form-item label="账号" :label-width="formLabelWidth">
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input
              v-model="form.password"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="(dialogFormVisible = false), confirmLogin()"
            >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 音乐列表 -->
      <el-main class="music-list-container">
        <div v-if="isLoading" class="loading-container">
          <el-icon class="is-loading" color="#ff4d4f" :size="40">
            <Loading />
          </el-icon>
        </div>

        <div v-else-if="errorMessage" class="error-container">
          <el-icon color="#ff4d4f" :size="40">
            <Warning />
          </el-icon>
          <p>{{ errorMessage }}</p>
        </div>

        <div v-else class="music-table">
          <div v-if="!ifLogin" class="login-prompt">
            <p
              style="
                color: #fff;
                font-size: 24px;
                text-align: center;
                padding: 40px;
              "
            >
              请先登录查看收藏歌曲
            </p>
          </div>

          <div v-else>
            <div class="table-header">
              <span class="title">歌曲名称</span>
              <span class="artist">歌手</span>
              <span class="action">操作</span>
            </div>
            <div class="table-body">
              <div
                v-for="music in currentPageData"
                :key="music.id"
                class="table-row"
                @click="goMusicDetail(music)"
              >
                <span class="title">{{ music.songtitle }}</span>
                <span class="artist">{{ music.songauthor }}</span>
                <el-icon
                  class="like-icon"
                  style="color: #ff4d4f"
                  @click.stop="toggleLike(music)"
                >
                  <Star />
                </el-icon>
              </div>
            </div>
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :background="true"
                layout="prev, pager, next"
                :total="filteredMusicList.length"
                @current-change="handlePageChange"
              />
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import axios from "axios";
import { useRouter } from "vue-router";
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  ArrowLeft,
  Search,
  Loading,
  Warning,
  Star,
} from "@element-plus/icons-vue";

const $router = useRouter();
const searchKeyword = ref("");

// 登录相关状态
const ifLogin = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = ref("120px");
const form = reactive({
  username: "",
  password: "",
});
const userInfo = reactive({
  userID: "",
  userInfoname: "",
  userToken: "",
});

// 音乐数据相关
const musicList = ref([]); // 已收藏的歌曲列表
const searchResults = ref([]); // 搜索结果列表

// 分页相关
const currentPage = ref(1);
const pageSize = ref(15);
const isLoading = ref(true);
const errorMessage = ref("");

// 处理搜索（仅在点击搜索按钮或回车时触发）
const handleSearch = () => {
  performSearch();
  currentPage.value = 1; // 搜索后重置到第一页
};

const handleEnterSearch = () => {
  performSearch();
  currentPage.value = 1; // 回车搜索后重置到第一页
};

const performSearch = () => {
  const keyword = searchKeyword.value.trim().toLowerCase();
  if (!keyword) {
    // 无关键词时显示全部收藏歌曲
    searchResults.value = [...musicList.value];
  } else {
    // 在收藏列表中按关键词搜索
    searchResults.value = musicList.value.filter(
      (music) =>
        music.songtitle?.toLowerCase().includes(keyword) ||
        music.songauthor?.toLowerCase().includes(keyword)
    );
  }
};

// 初始化检查登录状态
const checkLoginStatus = () => {
  const userID = localStorage.getItem("userID");
  const userToken = localStorage.getItem("userToken");
  const userInfoname = localStorage.getItem("userInfoname");

  if (userID && userToken) {
    ifLogin.value = true;
    userInfo.userID = userID;
    userInfo.userInfoname = userInfoname;
    userInfo.userToken = userToken;
  }
};

// 登录确认
const confirmLogin = async () => {
  try {
    const response = await axios.post("http://localhost:3001/api/login", {
      username: form.username,
      password: form.password,
    });

    if (response.data.user) {
      ElMessage.success("登录成功");
      ifLogin.value = true;
      localStorage.setItem("userID", response.data.user.id);
      localStorage.setItem("userInfoname", response.data.user.username);
      localStorage.setItem("userToken", response.data.user.token);
      userInfo.userInfoname = response.data.user.username;
      checkLoginStatus();
      await fetchMusicData(); // 登录成功后刷新数据
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.error("用户名或密码错误");
    } else {
      ElMessage.error("登录失败，请检查网络连接");
    }
  }
};

// 退出登录
const handleLogout = () => {
  ifLogin.value = false;
  ElMessage.success("退出登录成功");
  localStorage.removeItem("userID");
  localStorage.removeItem("userToken");
  localStorage.removeItem("userInfoname");
  userInfo.userID = "";
  userInfo.userInfoname = "";
  userInfo.userToken = "";
  form.username = "";
  form.password = "";
  musicList.value = [];
  searchResults.value = [];
};

// 注册跳转
const goToRegister = () => {
  $router.push("/register");
};

// 获取收藏音乐数据
const fetchMusicData = async () => {
  isLoading.value = true;
  errorMessage.value = "";
  try {
    const token = localStorage.getItem("userToken");
    if (!token) {
      errorMessage.value = "请先登录查看收藏歌曲";
      isLoading.value = false;
      return;
    }

    const response = await axios.get("http://localhost:3001/api/usersongs", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    musicList.value = response.data.map((music) => ({
      ...music,
      isLiked: true, // 已收藏状态
    }));
    searchResults.value = [...musicList.value]; // 初始化搜索结果为全部收藏歌曲
    isLoading.value = false;
  } catch (error) {
    console.error("数据获取失败:", error);
    errorMessage.value = "收藏列表加载失败，请稍后重试";
    isLoading.value = false;
  }
};

// 切换收藏状态（此处为删除收藏）
const toggleLike = async (music) => {
  try {
    const token = localStorage.getItem("userToken");
    if (!token) {
      ElMessage.warning("请先登录");
      return;
    }

    await axios.delete(`http://localhost:3001/api/usersongs/${music.id}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    // 从收藏列表和搜索结果中移除该歌曲
    const index = musicList.value.findIndex((m) => m.id === music.id);
    if (index !== -1) {
      musicList.value.splice(index, 1);
      searchResults.value = searchResults.value.filter(
        (m) => m.id !== music.id
      );
    }

    ElMessage.success("已取消收藏");
  } catch (error) {
    console.error("取消收藏失败:", error);
    ElMessage.error("取消收藏失败");
  }
};

// 跳转音乐详情
const goMusicDetail = (music) => {
  $router.push({
    name: "MusicDetail",
    params: { id: music.id },
  });
};

// 跳转到用户中心
const goUserInfo = () => {
  $router.push("/userinfo");
};

// 计算属性
const filteredMusicList = computed(() => searchResults.value);

const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredMusicList.value.slice(start, end);
});

// 生命周期钩子
onMounted(() => {
  checkLoginStatus();
  fetchMusicData();
});

// 分页处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
</script>

<style lang="scss" scoped>
$primary-color: #ff4d4f;
$dark-bg: #1a1a1a;
$text-primary: #ffffff;

.discover-container {
  height: 140vh;
  background: linear-gradient(45deg, #0a0a0a 0%, #1a1a1a 100%);
}

.discover-header {
  height: 140px;
  padding: 0 20px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(5px);
  border-bottom: 1px solid #333;

  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .search-container {
    flex: 1;
    max-width: 600px;
    margin: 0 30px;
    display: flex;
    gap: 10px;
    height: 40px;

    .search-input {
      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 20px;
        box-shadow: none;
        padding: 0 20px;

        .el-icon {
          color: #888;
          font-size: 18px;
        }

        input {
          color: $text-primary;

          &::placeholder {
            color: #666;
          }
        }
      }
    }

    .search-btn {
      border-radius: 20px;
      padding: 0 30px;
      font-weight: 500;
      letter-spacing: 1px;
      border: none;
      width: 68px;
      height: 40px;
      background-color: #ff4d4f;
    }

    .search-btn:hover {
      transition: background-color 0.3s;
      background-color: #ff1919;
    }
  }

  .back-home {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    color: $text-primary;
    transition: color 0.3s;

    &:hover {
      color: $primary-color;
    }

    .el-icon {
      font-size: 1.6rem;
    }

    span {
      font-size: 1.2rem;
    }
  }

  .user-info {
    .login-register {
      display: flex;
      gap: 20px;
      color: $text-primary;
      span {
        cursor: pointer;
        padding: 8px 16px;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
          color: $primary-color;
        }
      }
    }

    .user-info-content {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 8px 16px;
      cursor: pointer;
      transition: background 0.3s;

      &:hover {
        background: rgba(255, 255, 255, 0.05);
      }

      .user-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        border: 1px solid rgba(255, 255, 255, 0.1);
      }

      .user-name {
        color: $text-primary;
        font-size: 20px;
      }
    }
  }
}

.music-list-container {
  padding: 30px 20px;
  max-width: 1400px;
  margin: 0 auto;
  width: 1400px;
}

.music-table {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  overflow: hidden;
}

.table-header {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.08);
  color: #888;
  font-size: 14px;

  .title {
    flex: 2;
  }

  .artist {
    flex: 1;
  }

  .action {
    width: 80px;
    text-align: center;
  }
}

.table-body {
  .table-row {
    display: flex;
    align-items: center;
    padding: 16px 24px;
    transition: background 0.3s;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);

    &:hover {
      background: rgba(255, 255, 255, 0.03);
    }

    .title {
      flex: 2;
      color: $text-primary;
      font-size: 14px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .artist {
      flex: 1;
      color: #888;
      font-size: 14px;
    }

    .like-icon {
      width: 80px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s;
      font-size: 18px;

      &:hover {
        transform: scale(1.2);
      }
    }
  }
}

.pagination-container {
  padding: 20px 0;
  display: flex;
  justify-content: center;

  :deep(.el-pagination) {
    --el-pagination-bg-color: rgba(255, 255, 255, 0.05);
    --el-pagination-button-disabled-bg-color: transparent;
    --el-pagination-hover-color: $primary-color;
  }

  :deep(.el-pager) {
    li {
      background: rgba(255, 255, 255, 0.05);
      color: #666;
      border-radius: 8px;
      margin: 0 4px;
      min-width: 36px;
      height: 36px;

      &:not(.is-disabled):hover {
        background: rgba(255, 255, 255, 0.08);
        color: $primary-color;
      }

      &.is-active {
        background: $primary-color;
        color: white;
      }
    }
  }

  :deep(.btn-prev),
  :deep(.btn-next) {
    background: transparent;
    color: #666;
    border-radius: 8px;
    padding: 0 12px;

    &:not(.is-disabled):hover {
      color: $primary-color;
    }
  }
}

.loading-container,
.error-container {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;

  .el-icon {
    margin-bottom: 10px;
  }
}

.error-container {
  color: $primary-color;
}

:deep(.el-dialog) {
  background: #1e1e1e;
  border-radius: 12px;
  border: 1px solid #404040;

  .el-dialog__title {
    color: white;
  }

  .el-form-item__label {
    color: white !important;
  }

  .el-input__wrapper {
    background: #fff;
    margin-right: 30px;
  }
}
</style>
